package com.zwmuzhi.springcloud.loadbalanced;

import com.netflix.loadbalancer.IRule;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <h3>cloudLearn</h3>
 * <p>负载均衡算法</p>
 *
 * @author : zwmuzhi
 * @date : 2020-11-25 17:55
 **/
@Component
public class MyLoadBalanced implements IMyLoadBalanced {

    /**
     * 当前访问次数
     */
    private AtomicInteger currentCount = new AtomicInteger(0);

    @Override
    public ServiceInstance instance(List<ServiceInstance> serviceInstanceList) {
        //下一次要取的服务下标
        int servicesSize = serviceInstanceList.size();
        int index = incrementAndGetNext(servicesSize);
        return serviceInstanceList.get(index);
    }

    /**
     * 增加并返回当前访问次数
     * @return
     * @param servicesSize
     */
    private final int incrementAndGetNext(int servicesSize){

        int current;
        int next;

        do {
            current = this.currentCount.get();
            // 轮循核心公式
            next = (current + 1) % servicesSize;
            // 并发处理（自旋锁+原子类）
        }while (!this.currentCount.compareAndSet(current,next));

        return next;
    }


}
